/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.beans;

import com.smarttmt.idu.web.behavior.Preloadable;
import com.smarttmt.idu.web.model.User;
import com.smarttmt.idu.web.persistence.controller.ClasdoidJpaController;
import com.smarttmt.idu.web.persistence.controller.UsuacontJpaController;
import com.smarttmt.idu.web.persistence.entity.Clasdoid;
import com.smarttmt.idu.web.persistence.entity.Usuacont;
import com.smarttmt.idu.web.utilities.FacesUtils;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
@Named(value = "aditionalInformationBean")
@SessionScoped
public class AditionalInformation extends SmartIduBackingBean implements Serializable, Preloadable {

    private java.util.List<SelectItem> identificationTypeList;
    private String identificationTypeSelected;
    private User user;
    @PersistenceUnit(unitName = "smarttmtiduappPU")
    EntityManagerFactory emf;
    @Resource
    UserTransaction utx;
    private com.smarttmt.idu.web.persistence.controller.ClasdoidJpaController cl;
    private java.util.List<Clasdoid> listidType;
    private java.util.List<SelectItem> listIdTypeSelectItem;
    private UsuacontJpaController usuacontJpaController;
    private Usuacont usuacont;

    /**
     * Creates a new instance of aditionalInformation
     */
    public AditionalInformation() {
    }

    @PostConstruct
    public void initPostConstructoraditionalInformation() {
        usuacontJpaController = new UsuacontJpaController(utx, emf);
        cl = new ClasdoidJpaController(utx, emf);
        if (listidType == null) {
            listidType = new java.util.ArrayList<>();
        }
        listidType = cl.findClasdoidEntities();
        buildlistIdTypeSelectItem();
    }

    public void buildlistIdTypeSelectItem() {
        java.util.Iterator<Clasdoid> it = listidType.iterator();
        Clasdoid aux;
        if (listIdTypeSelectItem == null) {
            listIdTypeSelectItem = new java.util.ArrayList<>();
        }
        while (it.hasNext()) {
            aux = it.next();
            listIdTypeSelectItem.add(new SelectItem(aux.getCldicodi(), aux.getCldidesc(), aux.getCldidesc()));
        }
    }

    public void resetData() {
        user = new User();
        identificationTypeSelected = null;
    }

    public void refreshData() {

    }

    @Override
    public void preload(Map<String, Object> parameters) throws Exception {
        //Cuando se agreguen más atributos se requiere limpiarlo para cada vez que se ingrese a la opción
        resetData();
        buildIdentificationTypeList();
        String usuakey = (String) parameters.get("key");
        usuacont = new Usuacont();
        try {
            usuacont = usuacontJpaController.getUserByUsconomb(usuakey);
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "No ha sido posible obtener la informacion del usuario", ""));
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Señor Usuario, recuerde que la información suministrada en este formulario debe ser real, ya que se requerirá para futuros procesos.", "¡Por favor valídela antes de enviar!"));
    }

    private boolean isNumeric(String cadena) {
        try {
            Integer.parseInt(cadena);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }
    
    private boolean isBigNumeric(String cadena) {
        try {
            BigInteger bi =  new BigInteger(cadena);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }
    public String updateInformationUser() throws Exception {
        if (isBigNumeric(user.getIdentification())) {
            usuacont.setUscodoid(user.getIdentification());
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "La identificacion de usuario debe contener solo numeros", "Verificar Identificacion de usuario"));
            return null;
        }
        usuacont.setUscocldi(identificationTypeSelected);
        usuacont.setUscodire(user.getUserAddress());
        if (isBigNumeric(user.getUserMobilePhoneNumber()) && user.getUserMobilePhoneNumber().length() == 10) {
            usuacont.setUscotelm(user.getUserMobilePhoneNumber());
        } else {
            if (!isBigNumeric(user.getUserMobilePhoneNumber())) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "El número de móvil o de celular debe contener solo números", "Verificar número de teléfono"));
            }
            if (!(user.getUserMobilePhoneNumber().length() == 10)) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "El número de móvil o de celular debe tener un tamaño de 10", "Verificar número de teléfono"));
            }
            return null;
        }
        if (isNumeric(user.getUserTelephoneNumber()) && user.getUserTelephoneNumber().length() == 7) {
            usuacont.setUscotele(user.getUserTelephoneNumber());
        } else {
            if (!isNumeric(user.getUserTelephoneNumber())) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "El número de teléfono debe contener solo números", "Verificar número de teléfono"));
            }
            if (!(user.getUserTelephoneNumber().length() == 7)) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "El número de teléfono debe tener un tamaño de 7", "Verificar número de teléfono"));
            }
            return null;
        }
        usuacont.setUscoseap(user.getMiddleLastName());
        usuacont.setUscoprap(user.getFirstLastName());
        usuacont.setUscoprnm(user.getFirstName());
        usuacont.setUscosenm(user.getMiddleName());
        usuacontJpaController.edit(usuacont);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "La información adicional de usuario ha sido guardada exitosamente", ""));
        return "index";
    }

    public void buildIdentificationTypeList() {
        this.identificationTypeList = new java.util.ArrayList<>();

        //Se llama método para consultar los elementos en la DB
        //getOptionsForIdentificationTypeFromDB();
        this.identificationTypeList.add(new SelectItem(1, "Tarjeta de Identidad", "Tarjeta de Identidad"));
        this.identificationTypeList.add(new SelectItem(1, "Cédula de Ciudadanía", "Cédula de Ciudadanía"));
    }

    public List<SelectItem> getIdentificationTypeList() {
        return identificationTypeList;
    }

    public void setIdentificationTypeList(List<SelectItem> identificationTypeList) {
        this.identificationTypeList = identificationTypeList;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getIdentificationTypeSelected() {
        return identificationTypeSelected;
    }

    public void setIdentificationTypeSelected(String identificationTypeSelected) {
        this.identificationTypeSelected = identificationTypeSelected;
    }

    public EntityManagerFactory getEmf() {
        return emf;
    }

    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public UserTransaction getUtx() {
        return utx;
    }

    public void setUtx(UserTransaction utx) {
        this.utx = utx;
    }

    public ClasdoidJpaController getCl() {
        return cl;
    }

    public void setCl(ClasdoidJpaController cl) {
        this.cl = cl;
    }

    public List<Clasdoid> getListidType() {
        return listidType;
    }

    public void setListidType(List<Clasdoid> listidType) {
        this.listidType = listidType;
    }

    public List<SelectItem> getListIdTypeSelectItem() {
        return listIdTypeSelectItem;
    }

    public void setListIdTypeSelectItem(List<SelectItem> listIdTypeSelectItem) {
        this.listIdTypeSelectItem = listIdTypeSelectItem;
    }

    public UsuacontJpaController getUsuacontJpaController() {
        return usuacontJpaController;
    }

    public void setUsuacontJpaController(UsuacontJpaController usuacontJpaController) {
        this.usuacontJpaController = usuacontJpaController;
    }

    public Usuacont getUsuacont() {
        return usuacont;
    }

    public void setUsuacont(Usuacont usuacont) {
        this.usuacont = usuacont;
    }

}
